MATH.c

					
					/*
 * MATH_functions.c
 *
 *  Created on: 26 לא 2018 ד.
 *      Author: Bohdan
 */

#include "MATH_functions.h"
#include "stm32f4xx_hal.h"
#include "math.h"
#include "My_types.h"

/* Calculating of current RMS.
 * Parameters:
 * 		arr - pointer to array for calculating RMS
 * 		l - length of arr
 */
float calc_SKZ (int16_t* arr, int l, uint16_t Vref, SW_state_t state)
{
	uint16_t SKZ_ADC;
	uint32_t summ = 0;

	for(uint8_t i = 0; i < l; i++)
	{
		summ = summ + (int32_t)arr[i]*arr[i];
	}

	SKZ_ADC = (my_sqrt(summ/l));
	// Ka = 0/1 ֲ/ְ
	// I = N(אצן)*Uref/(2^12-1)/Ka
	// I = Nadc*12.1/Nvref   ("N" - מעסקוע ְײֿ)
	if(state == HIGH)
		return (float)((float)SKZ_ADC*12.1*2/(float)Vref);
	else
		return (float)((float)SKZ_ADC*12.1*0.5/(float)Vref);
}

uint32_t my_sqrt(uint32_t Val)
{
	int32_t ROOT = Val/2; // according to this algorithm, first value = half of argument under root
	for (int8_t i = 0; i<20; i++) // 14
	{
	    ROOT = (ROOT + Val/ROOT)/2;
	}
	return ROOT;
}

uint8_t calc_Spec(uint8_t size)
{
	uint8_t spec = 0;
	switch(size)
	{
	case 1: spec = 0x4F; break;
	case 2: spec = 0x4B; break;
	case 3: spec = 0x47; break;
	case 4: spec = 0x43; break;
	}

	return spec;
}